package com.oitsm.commons.dao;

import java.util.Collection;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
 * DAO 的基类
 * @author Arab Runner
 * Jun 25, 2011 12:10:53 PM
 */
@SuppressWarnings("unchecked")
public class BaseDaoImpl {
	private static final int INSERT_BATCH_SIZE = 20;
	
	private SessionFactory sessionFactory;

    protected SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
    protected Session getSession(){
    	return sessionFactory.getCurrentSession();
    }
    
	public List getAll(Class tClass){
    	Session session = this.getSession();
    	Criteria cri = session.createCriteria(tClass);
    	return cri.list();
    }
    public void save(Object entity){
    	this.getSession().save(entity);
    }
    public void saveAll(Collection objs){
    	saveAll(objs,INSERT_BATCH_SIZE);
    }
	public void saveAll(Collection objs,int batchSize){
    	Session session = this.getSession();
		int count = 0;
		for(Object obj : objs){
			count++;
			session.save(obj);
			if(count == batchSize){
				session.flush();
				session.clear();
				count = 0;
			}
		}
		if(count!=0){
			session.flush();
			session.clear();
		}
    }
    
    public void delete(Object entity){
    	this.getSession().delete(entity);
    }
    
	public void deleteAll(Collection entitys){
    	Session session = this.getSession();
    	for(Object entity : entitys){
    		session.delete(entity);
    	}
    }
    
    public void flushAndClear(){
    	Session session = this.getSession();
    	session.flush();
		session.clear();
    }
    
    public void update(Object entity) {
		Session session = this.getSession();
		session.update(entity);
	}

	public void updateAll(Collection<Object> objs) {
		Session session = this.getSession();
		for(Object obj : objs){
			session.update(obj);
		}
		
	}
}
